package jgl.vajra.driver.widget.retrofithelper.rxexception;


import jgl.vajra.driver.bean.LoginInfoBean;
import jgl.vajra.driver.manager.AccountManager;
import jgl.vajra.driver.widget.bean.BaseRequestData;
import jgl.vajra.driver.widget.manager.retrofit.RetrofitJsonManager;
import jgl.vajra.driver.widget.retrofithelper.utils.NetUtils;
import jgl.vajra.driver.widget.utils.UIUtils;
import com.orhanobut.logger.Logger;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2018/8/28.
 */

public class TokenInvalidInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if (NetUtils.isNetConnected(UIUtils.getContext()) && AccountManager.getInstance().isLogin()) {
            //  lock {
            // 判断token是否过期 1 过期 不需要处理 2,提前5分钟判断过期  其他表示正常
            boolean tokenInvalid = isTokenInvalid();
            if (tokenInvalid) {
                getNewTokenResponse(chain, request);
            }
            return chain.proceed(request);
        } else {
            return chain.proceed(request);
        }
    }

    private synchronized void getNewToken() {
        // AccountManager.getInstance().getNewToken();
    }

    public synchronized boolean isTokenInvalid() {
        LoginInfoBean loginInfo = AccountManager.getInstance().getLoginData(UIUtils.getContext());
        long currentTimeMillis = System.currentTimeMillis() / 1000;
        //判断过期时间  RefreshToken  用来表示登录失效 需要重新登录 提前2分钟

        //判断过期时间  AccessToken 用来刷新过期token 提前五分钟  LoginTime 在登录的时候记录一个登录时间, 用于判断登录多久了
        //long tokenTimeOut = loginInfo.tokenTime + 60 * 60 * 1000;
        long tokenTimeOut = loginInfo.tokenTime + 30000;
        if (currentTimeMillis + 300 >= tokenTimeOut) {
            return true;
        }
        return false;
    }

    private synchronized Response getNewTokenResponse(Chain chain, Request request) throws IOException {
        retrofit2.Response<BaseRequestData<LoginInfoBean>> execute = RetrofitJsonManager.getInstance().getApiService().refreshTokenCall().execute();
        if (execute.isSuccessful()) {
            BaseRequestData<LoginInfoBean> baseRequestData = execute.body();
            Logger.d(baseRequestData + "----body");
            if (baseRequestData.code == 0) {
                AccountManager.getInstance().saveLoginData(UIUtils.getContext(), baseRequestData.data);
                Request.Builder builder = request.newBuilder();
                //使用新的Token，创建新的请求
                builder.header("Authorization", baseRequestData.data.accessToken);
                Request build = builder.build();
                //重新请求
                return chain.proceed(build);
            }
        }
        return chain.proceed(request);
    }


}
